<template>
  <view>
    <BaseNavbar :title="title" />

    <BaseSearch :showScan="true" type-img="place" placeholder="请输入设备编号" @onClickIcon="onClickIcon" @search="search"
      @onClickScan="onClickScan" />
    <BaseDropdown :options-list="optionsList" @change="change" :num="deviceTotal" />
    <ComList :loading-type="loadingType">
      <DeviceListCard class="list-card" v-for="(item, index) in listData" :key="index" :info="item" :goShow="isShowGo"
        @onUnbind="onUnbind(item)" @deviceGoods="deviceGoods(item.device_sn)" @repl="repl(item.device_sn)"
        @onCard="onCard(item)" @remote="remote(item)" @updataTime="updataTime(item)" @autoOnOff="autoOnOff(item)"
        @onOff="onOff(item)" @goStart="goStart(item)" @others="other(item)" />
    </ComList>
    <BaseModal :show.sync="isShowModal" :content="'您的设备将与' + vPointName + '解除绑定，是否继续解绑？'" @confirm="confirmUnBind" />
    <BasePopup :show.sync="isShowPopup" mode="top" :customStyle="{
      top: 110 + vStatusBarHeight + vNavBarHeight + 'rpx',
    }">
      <DeviceScreener ref="DeviceScreener" @confirm="confirmScreenner"></DeviceScreener>
    </BasePopup>
    <!-- 开启 -->
    <BaseModal :show.sync="isShowDelModalOnOff" @confirm="confirmDelOnOff" :content="PopUps[index]" title="温馨提示">
    </BaseModal>
    <BaseModal :show.sync="isShowDelModalOff" @confirm="confirmDelOff" :content="index != 4 ? PopUps[index] : ''"
      :title="index != 4 ? '温馨提示' : ''">
      <view>
        <view>请选择要禁用的理由</view>
        <BaseRadio :radioIndex.sync="radioIndex" :list="reasonList" />
        <BaseInput v-if="radioIndex == 4" v-model="reason" placeholder="请输入禁用理由" />
      </view>
    </BaseModal>
    <BaseModal :show.sync="isShowStartModal" @confirm="confirmStart">
      <view slot="default">
        <BaseInput v-model="length_time" :disabled="vInputDisable" placeholder="请输入启动时长(分钟)" />
      </view>
    </BaseModal>
    <BasePopup :show.sync="showTaskType"  :maskClose="true" mode="center" height="400" :closeable="true" width="690"
      radius="20">
      <view class="pup_box">
        <view v-for="(item, i) in taskTypeList" :key="i">
          <BaseButton type="default" @onClick.stop="comfirmType(i)">
            {{ item }}
          </BaseButton>
        </view>
      </view>
    </BasePopup>
  </view>
</template>

<script>
import BaseDropdown from "@/components/base/BaseDropdown.vue";
import BaseNavbar from "@/components/base/BaseNavbar.vue";
import BaseSearch from "@/components/base/BaseSearch.vue";
import myPull from "@/mixins/myPull.js";
import ComList from "@/components/list/ComList.vue";
import DeviceListCard from "../components/cards/DeviceListCard.vue";
import BaseModal from "@/components/base/BaseModal.vue";
import BasePopup from "../../components/base/BasePopup.vue";
import DeviceScreener from "../components/screener/DeviceScreener.vue";
import BaseInput from "@/components/base/BaseInput.vue";
import BaseRadio from "../../components/base/BaseRadio.vue";
import BaseButton from "@/components/base/BaseButton.vue";
import { subtractDaysAndFormat } from "@/wxutil/times";
export default {
  components: {
    BaseNavbar,
    BaseSearch,
    BaseDropdown,
    ComList,
    DeviceListCard,
    BaseModal,
    BasePopup,
    DeviceScreener,
    BaseInput,
    BaseRadio,
    BaseButton
  },
  data() {
    return {
      title: "设备列表",
      fromData: "",
      isFromHome: false,
      isFromPlace: false,
      isFromScreenBindDevice: false,
      isShowStartModal: false,
      length_time: 1,
      optionsList: [
        {
          title: "全部",
          options: [
            { label: "全部", value: 0, status: 0 },
            {
              label: "在线",
              value: 1,
              status: 1,
            },
            {
              label: "离线",
              value: 2,
              status: 3,
            },
            {
              label: "3天未成交",
              value: 3,
              status: 3,
            },
            {
              label: "7天未成交",
              value: 4,
              status: 7,
            },
            {
              label: "30天未成交",
              value: 5,
              status: 30,
            }
          ],
          value: 0,
        },
      ],
      isShowModal: false,
      unBindItem: {},
      room_num: Number,
      status: 0,
      dianwei: 0,
      device_sn: "",
      hotel_id: 0,
      owner: "", //上级账号
      is_bind_hotel: false,
      deviceTotal: 0, //设备总数
      isShowPopup: true,
      isBind: 0, //筛选是否绑定 0全部 1已经绑定 2未绑定
      isShowDelModalOnOff: false,//开待机弹窗
      isShowDelModalOff: false,//禁用设备弹窗
      isShowGo: false,//启动其他设备来的
      PopUps: {
        0: '您确定要开启免费功能吗',
        1: '您确定要关闭免费功能吗',
        2: '您确定要开启自动待机功能吗',
        3: '您确定要关闭自动待机功能吗',
        4: '您确定要禁用该设备吗',
        5: '您确定要启用该设备吗',

      },//弹窗提示
      index: 0,//弹窗索引
      id: 0,//提交id
      items: {},
      reason: '',//禁用理由
      reasonList: [{
        title: "没电量了",
        name: "0",
        disabled: false,
        selectIndex: 0,

      }, {

        title: "无网络",
        name: "1",
        disabled: false,
        selectIndex: 1,

      }, {
        title: "没泡泡液",
        name: "2",
        disabled: false,
        selectIndex: 2,


      }, {

        title: "其他故障",
        name: "3",
        disabled: false,
        selectIndex: 3,

      }, {
        title: "其他理由",
        name: "4",
        disabled: false,
        selectIndex: 4,

      }],
      radioIndex: 0,
      showTaskType:false,
      taskTypeList: ['查询行为记录','开启开机自检','关闭开机自检'],
      lastest_order_time:'',
      isStatus:''
    };
  },
  methods: {
    comfirmType(i) {
      // console.log('选中的值', this.taskTypeList[i], this.info)
      this.showTaskType = false
      let e = this.taskTypeList[i]
      console.log('三个值', e, this.unBindItem)
      if (e == '查询行为记录') {
        uni.navigateTo({
          url:
            "/pagesD/History/History?data=" + encodeURIComponent(JSON.stringify(this.unBindItem))
        });
      } else if (e == '开启开机自检') {
        let data = {
          device_sn: this.device_sn,
          status: 1

        }
        this.$u.api.setPowerOnTestStatus(data).then((res) => {
          console.log("开启自检成功 ：", res);
          // this.refresh();
          this.isShowSuccess("操作成功");
        });
      } else if (e == '关闭开机自检') {
        let data = {
          device_sn: this.device_sn,
          status: 0

        }
        this.$u.api.setPowerOnTestStatus(data).then((res) => {
          console.log("关闭自检成功 ：", res);
          // this.refresh();
          this.isShowSuccess("操作成功");
        });
      }
    },
    loading(title, isShowLoading) {

      if (isShowLoading) {
        console.log('进来了')
        uni.showLoading({
          title,
          mask: true,
        })
      } else {
        uni.hideLoading()
      }
    },
    /* 更新时间 */
    async updataTime(item) {

      console.log(item)
      let parames = {
        device_sn: item.device_sn
      }
      let data = await this.$u.api.getAllStatus(parames)
      setTimeout(() => {
        this.loading('更新中', true)
      }, 100)
      setTimeout(() => {

        this.$u.api.getUMDetail(parames).then(res => {
          console.log('获取成功', res)
          this.items = item

          let index = this.listData.findIndex((items) => items.id === this.items.id); // 查找id为2的元素索引
          if (index !== -1) {
            // 如果找到了
            this.items.report_time = res.report_time
            this.items.light_status = res.light_status
            this.items.tip_music = res.tip_music
            this.items.electricity = res.electricity
            this.items.remain_game_time = res.remain_game_time
            this.items.electricity_status = res.electricity_status
            console.log('找到相同的', this.listData[index], this.items.use_status)
            this.listData.splice(index, 1, this.items);
            this.loading()
          }
        })
          .catch(err => {
            console.log('错误', err)
          })
      }, 3000)

    },
    other(item) {
      this.device_sn=item.device_sn
      this.showTaskType = true
      this.unBindItem = item;
    },
    onCard(item) {
      if (this.isFromScreenBindDevice) {
        let pages = getCurrentPages();
        let currPage = pages[pages.length - 1]; //当前页面
        let prevPage = pages[pages.length - 2]; //上一个页面
        //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
        prevPage.setData({
          item: item,
        });
        uni.navigateBack({
          delta: 1,
        });
      } else {
        uni.navigateTo({
          url:
            "/pagesB/device/DeviceDetail?from=device_list&device_sn=" +
            item.device_sn,
        });
      }
    },
    change(item) {
      this.optionsList = item;
      let index = item[0].value;
       this.isStatus = item[0].options[index].status;
      if (index<3) {
        this.lastest_order_time=''
       
      }else{

        this.lastest_order_time=subtractDaysAndFormat(item[0].options[index].status)
        console.log('日期',this.lastest_order_time)
      }
      // console.log("🚀 ~ this.status", this.status);
      this.refresh();
    },
    /* 开启自动待机 */
    autoOnOff(item) {
      if (item.is_auto_on_off !== 1) {
        this.index = 2;
      } else if (item.is_auto_on_off == 1) {
        this.index = 3
      }
      this.isShowDelModalOnOff = true
      this.id = item.id
    },
    /* 自动开关弹窗 */
    confirmDelOnOff() {
      let is_auto_on_off = 0;
      if (this.index == 2) {
        is_auto_on_off = 1;

      } else if (this.index == 3) {
        is_auto_on_off = 0;
      }

      let params = {
        id: this.id,
        is_auto_on_off,
      };

      // this.$u.api
      //   .setUpdateHotelAutoOnOffStatus(params)
      //   .then((res) => {
      //     console.log("成功返回信息", res);
      //       this.refresh();
      //   })
      //   .catch((err) => {
      //     console.log("成功返回信息", err);
      //   });

    },
    /* 禁用设备 */
    onOff(item) {
      if (item.use_status == 1) {
        this.index = 4;
      } else if (item.use_status == 2) {
        this.index = 5
      }
      this.isShowDelModalOff = true
      this.device_sn = item.device_sn
      console.log('禁用启动了', this.device_sn)
      this.items = item

    },
    /* 禁用设备弹窗 */
    async confirmDelOff() {
      console.log('禁用启动了', this.device_sn, this.radioIndex)
      let use_status = 0;
      if (this.index == 4) {
        use_status = 2;

      } else if (this.index == 5) {
        use_status = 1;
      }
      let title = ''
      if (use_status == 2) {

        if (this.radioIndex == 4) {
          title = this.reason
        } else {
          title = this.reasonList[this.radioIndex].title
        }
      }
      let params = {
        device_sn: this.device_sn,
        use_status,
        reason: title
      };
      this.$u.api
        .setupdateMachineStatus(params).then((res) => {
          console.log("成功返回信息", res);
          // this.refresh();
          let index = this.listData.findIndex((items) => items.id === this.items.id); // 查找id为2的元素索引
          if (index !== -1) {
            // 如果找到了
            if (this.items.use_status == 1) {
              this.items.use_status = 2
              this.items.reason = title

            } else if (this.items.use_status == 2) {
              this.items.use_status = 1
              this.items.reason = title

            }
            console.log('找到相同的', this.listData[index], this.items.use_status)
            this.listData.splice(index, 1, this.items);
          }
        })
        .catch((err) => {
          console.log("成功返回信息", err);
        });

    },
    /*启动设备 */
    goStart(item) {
      this.device_sn = item.device_sn
      this.isShowStartModal = true;
      console.log('点击了启动', item)

    },
    confirmStart() {
      // 开启游戏设备
      let data = {
        device_sn: this.device_sn,
        channel: 1, // 货道
        length_time: this.length_time,
      };

      this.$u.api.startUM(data).then((res) => {
        console.log("启动设备结果4 ：", res);
        // this.refresh();
        // this.isShowSuccess("操作成功", 1, () => { }, true);
      });
    },
    onClickIcon(e) {
      if (e == 0) {
        uni.navigateTo({ url: "/pagesB/mapMode/MapMode?from=device" });
      } else if (e == 1) {
        this.isShowPopup = !this.isShowPopup;
      }
    },
    getList(page, done) {
      this.isShowPopup = false;
      let data = {
        device_sn: this.device_sn,
        room_num: this.room_num,
        status: this.status, // 是否在线
        dianweiid: this.dianwei,
        hotel_id: this.hotel_id,
        page: page,
        owner: this.owner, //上级账号
        lastest_order_time:this.lastest_order_time
      }
      if(this.isStatus<4){
        data['status']=this.isStatus
      }else{
        data['status']=0
      }
        let rtnData = null;
      if (this.isBind) {
        data["is_bind_hotel"] = this.isBind == 1 ? true : false;
      }
      if (this.isFromHome || this.isFromScreenBindDevice) {
        rtnData = this.$u.api.getUserUMs(data);
        console.log('设备列表', rtnData)
      } else if (this.isFromPlace) {
        rtnData = this.$u.api.getHotelMachines({
          ...data,
          is_bind_hotel: this.is_bind_hotel,
        });
      }

      if (rtnData) {
        rtnData.then((res) => {
          this.deviceTotal = res?.total;
          done(res?.data);
        });
      }
    },
    onUnbind(item) {
      if (item.dianweiid && item.dianweiid > 0) {
        // 已经绑定了点位 弹出是否解绑
        this.unBindItem = item;
        this.isShowModal = true;
      } else {
        // 如果没有绑定点位，跳转到绑定点位界面
        uni.navigateTo({
          url:
            `/pagesB/place/BindPlace?from=device&device_sn=` +
            item.device_sn +
            "&mid=" +
            item.id,
        });
      }
    },
    confirmUnBind() {
      //确认解绑
      let data = {
        device_sn: this.unBindItem.device_sn,
      };

      this.$u.api.unbindHotel(data).then((res) => {
        this.isShowSuccess("解绑成功", 0, () => this.refresh());
      });
      console.log("确认解绑");
    },
    deviceGoods(device_sn) {
      uni.navigateTo({
        url: `/pagesB/device/DeviceGoodsList?from=device&device_sn=${device_sn}`,
      });
    },
    search(val) {
      this.device_sn = val;
      this.refresh();
    },
    repl(device_sn) {
      uni.navigateTo({
        url:
          "/pagesB/device/DeviceGoodsList?from=replenish&device_sn=" +
          device_sn,
      });
    },
    /* 遥控 */
    remote(item) {
      uni.navigateTo({
        url:
          `/pagesB/remote/RemoteEquipment?from=replenish&device_sn=` +
          item.device_sn +
          "&mid=" +
          item.id,
      });
    },
    //点击扫码icon
    onClickScan(result, option) {
      console.log("🚀 ~ result", result);
      console.log("🚀 ~ option", option);
      if (!result) return this.isShowErr("请扫描正确二维码~");
      if (option) {
        if (option.vscode) {
          this.device_sn = option.vscode;
        } else if (option.device_sn) {
          this.device_sn = option.device_sn;
        } else if (option.mid) {
          this.device_sn = option.mid;
        } else {
          this.device_sn = result;
        }
      } else {
        this.device_sn = result;
        // this.isShowErr("未扫描设备码~");
      }
      this.refresh();
      this.device_sn = "";
    },
    confirmScreenner(e) {
      console.log("🚀 ~ e", e);
      this.device_sn = e.device_sn;
      this.room_num = e.room_num;
      this.status = e.status;
      // this.dianwei = e.dianwei;
      this.hotel_id = e.dianwei;
      this.owner = e.owner;
      // this.isBind = e.is_bind_hotel;
      this.isShowPopup = false;
      this.refresh();
    },
  },
  onLoad(opt) {
    this.fromData = opt?.from;
    if (this.fromData == "place") {
      //点位来的
      this.title = `${this.vPointName}设备`;
      this.isFromPlace = true;
      this.dianwei = opt.dianwei;
      this.hotel_id = opt.hotel_id;
      this.is_bind_hotel = true;
    } else if (this.fromData == "go") {
      //点位来的
      this.title = `${this.vPointName}设备`;
      this.isFromPlace = true;
      this.isShowGo = true;
      this.dianwei = opt.dianwei;
      this.hotel_id = opt.hotel_id;
      this.is_bind_hotel = true;
    } else if (this.fromData == "screen_bind_device") {
      this.title = "选择设备";
      this.isFromScreenBindDevice = true;
    } else if (this.fromData == "device") {
      this.title = "设备列表";

      this.isFromScreenBindDevice = true;
      this.optionsList[0].value = opt.status;
      this.optionsList[0].title = opt.status == '1' ? '在线' : opt.status == '2' ? '异常' : opt.status == '3' ? '离线' : '全部';

      this.status = opt.status;
      // console.log("🚀 ~ this.status", this.status);
      // this.refresh();
      console.log("opt传过来的值", this.optionsList);
    } else {
      this.isFromHome = true;
    }
    if(this.vInputDisable){
      this.length_time=this.vTime
    }
    this.refresh();
  },
  onShow(e) {
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1]; // 当前页
    if (currPage.data.isDoRefresh == true) {
      // 是否刷新
      currPage.data.isDoRefresh = false;
      this.refresh();
    }
    if (currPage.data.item && this.isShowPopup) {
      let checkHotel = currPage.data.item;
      this.$refs.DeviceScreener.hotelName = checkHotel.hotelName;
      this.$refs.DeviceScreener.hotel_id = checkHotel.id;
    }
  },
  mixins: [myPull()],
};
</script>
<style lang="scss">
page {
  background-color: $pageBgColor;
}
</style>

<style lang="scss" scoped>
.pup_box {
  padding: 20rpx;
  padding-top: 40rpx;
  display: flex;
  flex-wrap: wrap;
  >view{
    width: 270rpx;
    margin: 20rpx;
  }
}
</style>
